package com.sk.weichat.view.chatHolder;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.view.SimpleDraweeView;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.downloader.DownloadListener;
import com.sk.weichat.downloader.Downloader;
import com.sk.weichat.downloader.FailReason;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.message.ChatOverviewActivity;
import com.sk.weichat.ui.mucfile.XfileUtils;
import com.sk.weichat.ui.tool.SingleImagePreviewActivity;
import com.sk.weichat.util.FileUtil;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.view.ChatImageView;
import com.sk.weichat.view.XuanProgressPar;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import pl.droidsonroids.gif.GifDrawable;

public class ImageViewHolder extends AChatHolderInterface {

    private static final int IMAGE_MIN_SIZE = 118; // dp
    private static final int IMAGE_MAX_SIZE = 194;
    //ChatImageView mImageView;
    SimpleDraweeView mImageView;
    XuanProgressPar progressPar;
    private int width, height;
    private TextView mTvFileName;
    private TextView mTvFileSize;
    private RelativeLayout mLayoutBottomInfo;

    public ImageViewHolder(@NonNull View itemView) {
        super(itemView);
    }

    @Override
    public int itemLayoutId(boolean isMysend) {
        return isMysend ? R.layout.chat_from_item_image : R.layout.chat_to_item_image;
    }

    @Override
    public void initView(View view) {
        mImageView = view.findViewById(R.id.chat_image);

        mLayoutBottomInfo = view.findViewById(R.id.layout_bottom_info);
        mTvFileName = view.findViewById(R.id.tv_file_name);
        mTvFileSize = view.findViewById(R.id.tv_file_size);

        progressPar = view.findViewById(R.id.img_progress);
        mRootView = view.findViewById(R.id.chat_warp_view);
    }

    @Override
    public void fillData(ChatMessage message) {
        // 修改image布局大小，解决不能滑动到底部的问题
//        changeImageLayaoutSize(message, IMAGE_MIN_SIZE, IMAGE_MAX_SIZE);
//
        float image_width;
        float image_height;
        if (TextUtils.isEmpty(message.getLocation_x()) || TextUtils.isEmpty(message.getLocation_y())) {
            image_width = dp2px(IMAGE_MIN_SIZE);
            image_height = dp2px(IMAGE_MAX_SIZE);
        } else {
            image_width = Float.parseFloat(message.getLocation_x());
            image_height = Float.parseFloat(message.getLocation_y());
        }
        float[] size = getScaleSize(image_width, image_height);
        String filePath = message.getFilePath();
        if (FileUtil.isExist(filePath)) { // 本地存在
            //Log.e("lzs", "本地存在");
            FrescoUtils.loadFile(mImageView, filePath);
        } else {
            FrescoUtils.loadImage((SimpleDraweeView) mImageView, message.getContent(), (int) size[0], (int) size[1], new FrescoUtils.ProgressResponseBody.ProgressListener() {
                @Override
                public void update(long bytesRead, long contentLength, boolean done) {
                    mSendingBar.setVisibility(done ? View.GONE : View.VISIBLE);
                    // progressPar.update((int) (bytesRead / contentLength));
                }
            });
        }
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mImageView.getLayoutParams();
        lp.width = (int) size[0];
        lp.height = (int) size[1];
        mImageView.setLayoutParams(lp);
        ConstraintLayout.LayoutParams mLayoutBottomParams = (ConstraintLayout.LayoutParams) mLayoutBottomInfo.getLayoutParams();
        mLayoutBottomParams.width = (int) size[0];
        mLayoutBottomInfo.setLayoutParams(mLayoutBottomParams);
//        Log.e("lzs", "width:" + mLayoutBottomParams.width);
//        Log.e("lzs", "type:" + message.getType());
        if (message.getType() == XmppMessage.TYPE_FILE) {//图片文件
            mLayoutBottomInfo.setVisibility(View.VISIBLE);
            mTvFileName.setText(message.getFilePath().substring(message.getFilePath().lastIndexOf("/") + 1));
            mTvFileSize.setText(XfileUtils.fromatSize(message.getFileSize()));
        } else {
            mLayoutBottomInfo.setVisibility(View.INVISIBLE);
        }

        // 判断是否为阅后即焚类型的图片，如果是 模糊显示该图片
        if (!isGounp) {
            mImageView.setAlpha(message.getIsReadDel() ? 0.1f : 1f);
        }

        // 上传进度条 我的消息才有进度条
        if (message.isUpload() || !isMysend || message.getUploadSchedule() >= 100) {
            progressPar.setVisibility(View.GONE);
        } else {
            progressPar.setVisibility(View.VISIBLE);
        }
        progressPar.update(message.getUploadSchedule());
    }

    private float[] getScaleSize(float originalW, float originalH) {
        float[] outSize = new float[2];
        int min = dp2px(IMAGE_MIN_SIZE);
        int max = dp2px(IMAGE_MAX_SIZE);
        //Log.e("lzs", "min:" + min + " max:" + max);
        if (originalW > originalH) {
            if (originalW < min) {
                outSize[0] = min;
                outSize[1] = originalH * 1.0f / originalW * min;
            } else {
                float scale = originalH * 1.0f / originalW;
                if (scale < 0.3) {
                    //图片特别宽，高度设置为最大高度的一半
                    outSize[1] = max / 2;
                } else {
                    //限制高度不能超过最大高度
                    outSize[1] = Math.min((int) (scale * min), max);
                }
                outSize[0] = min;
            }
        } else if (originalW == originalH) {
            outSize[0] = min;
            outSize[1] = min;
        } else {
            if (originalH < max) {
                if (originalW > min) {
                    //如果原始宽度大于最大宽度，需要缩放
                    outSize[0] = min;
                    float scale = originalW * 1.0f / min;
                    outSize[1] = originalH * scale;
                } else {
                    outSize[0] = originalW;
                    outSize[1] = originalH;
                }
            } else {
                float scale = originalW * 1.0f / originalH;
                if (scale < 0.3) {
                    //长宽比例较大,图片特别长，宽度设置为最大宽度的一半
                    outSize[0] = min / 2;
                } else {
                    //取原图按比例缩放后的值和最大宽度中较小者
                    outSize[0] = Math.min((int) (scale * max), min);
                }
                outSize[1] = max;
            }
        }
        return outSize;
    }

    private void fillImageGif(String filePath) {
        try {
            GifDrawable gifFromFile = new GifDrawable(new File(filePath));
            // mImageView.setImageGifDrawable(gifFromFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void changeImageLayaoutSize(ChatMessage message, int mindp, int maxdp) {
        ViewGroup.LayoutParams mLayoutParams = mImageView.getLayoutParams();

        if (TextUtils.isEmpty(message.getLocation_x()) || TextUtils.isEmpty(message.getLocation_y())) {
            mLayoutParams.width = dp2px(maxdp);
            mLayoutParams.height = dp2px(maxdp);

            width = mLayoutParams.width;
            height = mLayoutParams.height;
            Downloader.getInstance().addDownload(message.getContent(), mSendingBar, new FileDownloadListener(message, mImageView));
        } else {
            float image_width = Float.parseFloat(message.getLocation_x());
            float image_height = Float.parseFloat(message.getLocation_y());

            // 基于宽度进行缩放,三挡:宽图 55/100,窄图100/55
            float width = image_width / image_height < 0.4 ? mindp : maxdp;
            float height = width == maxdp ? Math.max(width / image_width * image_height, mindp) : maxdp;

            mLayoutParams.width = dp2px(width);
            mLayoutParams.height = dp2px(height);

            this.width = mLayoutParams.width;
            this.height = mLayoutParams.height;
        }

        mImageView.setLayoutParams(mLayoutParams);

        ViewGroup.LayoutParams mLayoutBottomParams = mLayoutBottomInfo.getLayoutParams();
        mLayoutBottomParams.width = width;
        mLayoutBottomInfo.setLayoutParams(mLayoutBottomParams);
    }

    @Override
    public void onRootClick(View v) {
        if (mdata.getIsReadDel()) { // 阅后即焚图片跳转至单张图片预览类
            Intent intent = new Intent(mContext, SingleImagePreviewActivity.class);
            intent.putExtra(AppConstant.EXTRA_IMAGE_URI, mdata.getContent());
            intent.putExtra("image_path", mdata.getFilePath());
            intent.putExtra("isReadDel", mdata.getIsReadDel());
            if (!isGounp && !isMysend && mdata.getIsReadDel()) {
                intent.putExtra("DEL_PACKEDID", mdata.getPacketId());
            }
            mContext.startActivity(intent);
        } else {
            int imageChatMessageList_current_position = 0;
            List<ChatMessage> imageChatMessageList = new ArrayList<>();
            for (int i = 0; i < chatMessages.size(); i++) {
                if ((chatMessages.get(i).getType() == XmppMessage.TYPE_IMAGE
                        || (chatMessages.get(i).getType() == XmppMessage.TYPE_FILE//图片文件
                        && ChatHolderFactory.getChatHolderType(true, chatMessages.get(i)) == ChatHolderFactory.ChatHolderType.VIEW_FROM_FILE_IMAGE))
                        && !chatMessages.get(i).getIsReadDel()) {

                    if (chatMessages.get(i).getPacketId().equals(mdata.getPacketId())) {
                        imageChatMessageList_current_position = imageChatMessageList.size();
                    }
                    imageChatMessageList.add(chatMessages.get(i));
                }
            }
            Intent intent = new Intent(mContext, ChatOverviewActivity.class);
            intent.putExtra("imageChatMessageList", JSON.toJSONString(imageChatMessageList));
            intent.putExtra("imageChatMessageList_current_position", imageChatMessageList_current_position);
            mContext.startActivity(intent);
        }
    }

    @Override
    public boolean enableSendRead() {
        return true;
    }

    // 启用阅后即焚
    @Override
    public boolean enableFire() {
        return true;
    }

    class FileDownloadListener implements DownloadListener {
        private ChatMessage message;
        private ImageView imageView;

        public FileDownloadListener(ChatMessage message, ImageView imageView) {
            this.message = message;
            this.imageView = imageView;
        }

        @Override
        public void onStarted(String uri, View view) {
            if (view != null) {
                view.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onFailed(String uri, FailReason failReason, View view) {
            if (view != null) {
                view.setVisibility(View.GONE);
            }
        }

        @Override
        public void onComplete(String uri, String filePath, View view) {
            if (view != null) {
                view.setVisibility(View.GONE);
            }
            message.setFilePath(filePath);
            ChatMessageDao.getInstance().updateMessageDownloadState(mLoginUserid, mToUserId, message.get_id(), true, filePath);
            if (filePath.endsWith(".gif")) { // 加载gif
                fillImageGif(filePath);
            } else { // 保存图片尺寸到数据库
                saveImageSize(filePath);
            }
        }

        @Override
        public void onCancelled(String uri, View view) {
            if (view != null) {
                view.setVisibility(View.GONE);
            }
        }

        private void saveImageSize(String filePath) {
            //
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options); // 此时返回的bitmap为null

            message.setLocation_x(String.valueOf(options.outWidth));
            message.setLocation_y(String.valueOf(options.outHeight));
//            Log.e("lzs", "options.outWidth:" + options.outWidth);
//            Log.e("lzs", "options.outHeight:" + options.outHeight);
            // 重绘图片尺寸
            changeImageLayaoutSize(message, IMAGE_MIN_SIZE, IMAGE_MAX_SIZE);
            AvatarHelper.getInstance().displayUrl(filePath, mImageView, R.drawable.fez);
            // 保存下载到数据库
            ChatMessageDao.getInstance().updateMessageLocationXY(message, mLoginUserid);
        }
    }
}
